//
//  UPOrderViewController.m
//  LoveFreshBee
//
//  Created by wyzc on 16/6/8.
//  Copyright © 2016年 叶落知秋. All rights reserved.
//

#define URLSTR @"http://api.beequick.cn/home/products?zchtid=5302&bigids=2,0&self_dealer=0&designated_dealerid=0&delivery_type=0&g_uniqid=920d4d006456f94b7b9075676b62738b&zchtauth=94491eAqgap6WCGNmyeWUSiIKwjIyUXmSd3Yksk81zGxpCZFk&g_screen_points=375x667&g_product=BEE&NetworkType=wifi&g_screen_pixels=750x1334&sys_version=9.3&g_platform=IOS&g_channel=60001&g_sessionid=iPho20160612095824f0cfcaa3618baaccd8462f9ea9e088d9&g_phone=13932150201&location=116.404276%2C39.906534&GPS_LatLng=114.483699%2C38.048383&ServiceProvider=%E4%B8%AD%E5%9B%BD%E7%A7%BB%E5%8A%A8&__d=d14ryS1QFkJ2ebYyrPMrTD%2F97V%2BrB61dlw03aQFPxPFNOpbjqJM5HpTIlnwAZPd5UyoGA1lWqRnthC%2F8VoGEP0ul3q6Zmr3MjBwz%2BqOsgDKP4dDkO1uU%2B87XpBNwx14eK17f&__v=ios5.3&phoneType=iPhone+6+%28A1549%2FA1586%29&g_version=3.31&timestamp=1465696731008541&token=920d4d006456f94b7b9075676b62738b&mac=6686dfe7bbd5d53924b6d4be8198a512"


#define CATEGORYCELLID @"CATEGORY"

#define PRODUCTCELLID @"PRODUCT"

#import "UPOrderViewController.h"
#import <AFNetworking.h>
#import "UPOrderCategoryModel.h"
#import "UPOrderCategoryCell.h"
#import "UPOrderProductCell.h"
#import "UPOrderProductModel.h"
#import "UPOrderProductDetailViewController.h"
#import "UPHButton.h"
#import "UPOederAllClassModel.h"
#import <CoreLocation/CoreLocation.h>
#import "UPOrderSearchViewController.h"

@interface UPOrderViewController ()<UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *categoryTable;
@property (weak, nonatomic) IBOutlet UITableView *productTableView;

/**
 *  存放左边tableview的数据源
 */
@property(nonatomic,strong)NSMutableArray *categoryDataSource;

/**
 *  存放右边tableview的数据源
 */
@property(nonatomic,strong)NSMutableArray *productDateSource;
/**
 *  存放products的字典
 */
@property(nonatomic,strong)NSDictionary *productsDict;
/**
 *  存放全部分类的view
 */
@property(nonatomic,weak)UIView *buttonView;
/**
 *  存放分类按钮的遮盖层
 */
@property(nonatomic,weak) UIButton *coverBtn;
/**
 *  存放全部分类的按钮
 */
@property (weak, nonatomic) IBOutlet UPHButton *allClassButton;
/**
 *  综合排序按钮
 */
@property (weak, nonatomic) IBOutlet UPHButton *sortButton;
/**
 *  存放综合排序的view
 */
@property(nonatomic,weak)UIView *rightView;

@property(nonatomic,weak)UIButton *coverBtn1;

/**
 *  保存当前背景颜色为红色的按钮
 */
@property(nonatomic,weak) UIButton *redButton;
/**
 *  保存当前红色按钮在buttonview中的索引
 */
@property(nonatomic,assign)int redButtonIndex;
/**
 *  备份数据
 */
@property(nonatomic,strong)NSMutableArray *productDataSourBak;
/**
 *  存放分类排序当前红色的按钮
 */
@property(nonatomic,weak)UIButton *rightButton;
/**
 *  保存分类排序当前红色按钮在buttonview中的索引
 */
@property(nonatomic,assign)int rightIndex;
/**
 *  保存右边按钮名字
 */
//@property(nonatomic,copy)NSString *nameStr;
/**
 *  位置管理器
 */
@property(nonatomic,strong)CLLocationManager *locationManager;
@end

@implementation UPOrderViewController
-(CLLocationManager *)locationManager
{
    if (_locationManager==nil) {
        _locationManager=[[CLLocationManager alloc] init];
        //把当前控制器设置为定位管理器的代理
        _locationManager.delegate=self;
        //设置定位精度
        _locationManager.desiredAccuracy=kCLLocationAccuracyBestForNavigation;
    }
    return _locationManager;
}

-(NSMutableArray *)categoryDataSource
{
    if (_categoryDataSource==nil) {
        _categoryDataSource=[NSMutableArray array];
    }
    return _categoryDataSource;
}

-(NSMutableArray *)productDateSource
{
    if (_productDateSource==nil) {
        _productDateSource=[NSMutableArray array];
    }
    return _productDateSource;
}
-(NSMutableArray *)productDataSourBak
{
    if (_productDataSourBak==nil) {
        _productDataSourBak=[NSMutableArray array];
    }
    return _productDataSourBak;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.redButtonIndex=-1;
    self.rightIndex=-1;
    
    //保存按钮名字
   // self.nameStr=self.sortButton.titleLabel.text;
    //设置背景颜色
    //self.view.backgroundColor=[UIColor redColor];
    //设置导航条颜色
    self.navigationController.navigationBar.barTintColor=UPColor(255, 218, 0);
    //设置categorytableview的背景颜色
    self.categoryTable.backgroundColor=UPColor(248, 248, 248);
    [self setNavBar];
    [self setSearch];
    [self registerXib];
    [self sendRequest];
    [self getCurrentLocation];
    
    
    
}
/**
 *  通过定位获取经纬度，然后再通过编码获取当前的地名
 */
-(void)getCurrentLocation
{
    AFNetworkReachabilityManager *manager=[AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
                
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            //判断定位服务是否（可以使用）已经打开
                [self beginLocation];
                break;
                
            default:
                break;
        }
    }];
    [manager startMonitoring];
    
}
/**
 *  判断定位服务是否（可以使用）已经打开
 */
-(void)beginLocation
{   //判断定位服务是否（可以使用）已经打开
    if (![CLLocationManager locationServicesEnabled]) {
        return;
    }
    //判断系统是否已经给当前应用程序授权
    if (CLLocationManager.authorizationStatus!=kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    //开始定位
    [self.locationManager startUpdatingLocation];
}

//添加扫描按钮
-(void)setNavBar
{
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    [btn addTarget:self action:@selector(btnLeftClick) forControlEvents:UIControlEventTouchUpInside];
    
    [btn setBackgroundImage:[UIImage imageNamed:@"icon_black_scancode"]forState:UIControlStateNormal];
    
    UIBarButtonItem *leftItem=[[UIBarButtonItem alloc]initWithCustomView:btn];
    
    self.navigationItem.leftBarButtonItem=leftItem;
}
//添加搜索按钮
-(void)setSearch
{
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    [btn addTarget:self action:@selector(btnRightSearch) forControlEvents:UIControlEventTouchUpInside];
    
    [btn setBackgroundImage:[UIImage imageNamed:@"icon_search"] forState:UIControlStateNormal];
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem=rightItem;
    
}

//注册 tablevewcell的xib 
-(void)registerXib
{
    //如果一个方法的行参是bundel的话，设置nil的话，就代表[nsbundle mainbundel]
    UINib *categoryNib=[UINib nibWithNibName:@"UPOrderCategory" bundle:nil];
    [self.categoryTable registerNib:categoryNib forCellReuseIdentifier:CATEGORYCELLID];
    
    UINib *productNib=[UINib nibWithNibName:@"UPOrderProductCell" bundle:nil];
    
    [self.productTableView registerNib:productNib forCellReuseIdentifier:PRODUCTCELLID];
}

//点击按钮，调用方法
-(void)btnLeftClick
{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//点击放大镜，调用方法
-(void)btnRightSearch
{
    UPOrderSearchViewController *searchVC=[[UPOrderSearchViewController alloc] init];
    
    [self.navigationController pushViewController:searchVC animated:YES];
    
}



//向服务器发送请求，这样就可以得到从服务器返回过来的数据
-(void)sendRequest
{
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    [manager GET:@"http://m.beequick.cn/data/getCategoryProduct?asid=575d18dda79993326&_r=0.09407075636470152&tg=&tn=&reflogid=575d1fca7e9844954&zchtid=3248&bigids=2%2C0" parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *responseDict) {
        //把字典放到plist文件中去
       // [responseDict writeToFile:@"/Users/wyzc/Desktop/LoveFreshBee.plist" atomically:YES];
        
        NSDictionary *dataDict=responseDict[@"data"];
        
        if (dataDict==nil) {
//            NSString *path=[[NSBundle mainBundle]pathForResource:@"LoveFreshBee.plist" ofType:nil];
//            
//            responseDict=[NSDictionary dictionaryWithContentsOfFile:path];
//            
//            dataDict=responseDict[@"data"];
            return ;
        }
        NSArray *categories=dataDict[@"categories"];
        
        for (NSDictionary *categoryDict in categories) {
            UPOrderCategoryModel *model=[UPOrderCategoryModel categoryWithDict:categoryDict];
            
            [self.categoryDataSource addObject:model];
            
        }
        //刷新左边的tableview
        [self.categoryTable reloadData];
        
        
        //选中某一行
        NSIndexPath *path=[NSIndexPath indexPathForRow:0 inSection:0];
        [self.categoryTable selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionTop];
        
       
        
        //获取右边tablev要显示的数据
        NSDictionary *productsDict=dataDict[@"products"];
        
        self.productsDict=productsDict;
        
        UPOrderCategoryModel *firsitCategory=self.categoryDataSource[0];
        
        NSString *firstId=[NSString stringWithFormat:@"%d",firsitCategory.iid];
        
        NSArray *productArr=productsDict[firstId];
        
        for (NSDictionary *pDict in productArr) {
            UPOrderProductModel *model=[UPOrderProductModel productWithDict:pDict];
            
            [self.productDateSource addObject:model];
            
            
        }
        [self.productDataSourBak addObjectsFromArray:self.productDateSource];
        
        
        //刷新右边tableview
        [self.productTableView reloadData];

        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}
//全部分类按钮点击事件
- (IBAction)btnAllClassClick:(id)sender {
    
    UPHButton *hbtn=(UPHButton *)sender;
    UIImageView *imgView=hbtn.imageView;
    [UIView animateWithDuration:0.5 animations:^{
    imgView.transform=CGAffineTransformRotate(imgView.transform, -M_PI);
    }];
    
    
    if (self.buttonView) {
        [self.buttonView removeFromSuperview];
        self.buttonView=nil;
        
        [self.coverBtn removeFromSuperview];
        self.coverBtn=nil;
        return;
    }
    
    if (self.rightView) {
        [self.rightView removeFromSuperview];
        
        [self.coverBtn1 removeFromSuperview];
        self.coverBtn1=nil;
        
        UIImageView *imgView=self.sortButton.imageView;
        [UIView animateWithDuration:0.5 animations:^{
            imgView.transform=CGAffineTransformRotate(imgView.transform, -M_PI);
        }];
        
        
    }
    if (self.categoryDataSource.count==0) {
        return;
    }
    
    //1.获取选中的category模型，cids
    //获取选中行
    NSIndexPath *selectedIndexPath=self.categoryTable.indexPathForSelectedRow;
    UPOrderCategoryModel *categoryModel=self.categoryDataSource[selectedIndexPath.row];
    NSArray *cids=categoryModel.cids;
    
    
    
    //创建一个存放所有按钮的view
    UIView *buttonView=[[UIView alloc] initWithFrame:CGRectMake(self.productTableView.x, self.productTableView.y, self.productTableView.bounds.size.width, 0)];
    
    
    //创建一个点击手势
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideButtonView)];
    //把手势添加到view中
    [buttonView addGestureRecognizer:tap];
    
    
    self.buttonView=buttonView;
    buttonView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:buttonView];
    
    
    //间距
    int margin=5;
    int btnH=30;
    CGFloat btnW=(self.productTableView.bounds.size.width-4*margin)*0.33;
    for (int i=0; i<cids.count; i++) {
        int col=i%3;//确定列
        int row=i/3;//确定行
        //计算X坐标
        CGFloat btnX=margin+(margin+btnW)*col;
        //计算Y坐标
        CGFloat btnY=margin+(margin+btnH)*row;
        
        UPOederAllClassModel *model=cids[i];
        
        UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(btnX, btnY, btnW, btnH)];
        
        //字体大小
        btn.titleLabel.font=[UIFont systemFontOfSize:13];
        
        CALayer *layer=btn.layer;
        
        layer.borderColor=UPColor(169, 169, 169).CGColor;
        layer.borderWidth=1;
        layer.cornerRadius=5;
        
        
        btn.tag=i;
        //按钮点击事件
        [btn addTarget:self action:@selector(changeProducts:) forControlEvents:UIControlEventTouchUpInside];
        
        
        //说明之前已经点击过某个按钮了
        if (self.redButtonIndex>=0) {
            if (self.redButtonIndex==i) {
                self.redButton=btn;
                [btn setBackgroundColor:[UIColor redColor]];
            }
        }
        else//第一次被打开
        {
            if (i==0) {
                [btn setBackgroundColor:[UIColor redColor]];
                self.redButtonIndex=0;
                self.redButton=btn;//保存当前红色按钮
            }
        }
        
        [buttonView addSubview:btn];
        [btn setTitle:model.name forState:UIControlStateNormal];
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    
    
    
    
    //计算总行数
    int rowCount=(cids.count%3)?(int)cids.count/3+1:(int)cids.count/3;
    
    int height=rowCount*(margin+btnH)+margin;
   
    buttonView.height=height;
    
    
    //在buttonview的下面添加半透明的遮盖view
    UIButton *coverBtn=[[UIButton alloc] initWithFrame:CGRectMake(self.productTableView.x,buttonView.height+self.productTableView.y , self.productTableView.width, self.productTableView.height-buttonView.height)];
    
    self.coverBtn=coverBtn;
    
    coverBtn.backgroundColor=[UIColor blackColor];
    coverBtn.alpha=0.3;
    
    [coverBtn addTarget:self action:@selector(removeCover) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:coverBtn];
    
    
    
}

-(void)removeCover
{
    
    UIImageView *imgView=self.allClassButton.imageView;
    [UIView animateWithDuration:0.5 animations:^{
        imgView.transform=CGAffineTransformRotate(imgView.transform, -M_PI);
    }];
    
    if (self.buttonView) {
        [self.buttonView removeFromSuperview];
        self.buttonView=nil;
        
        [self.coverBtn removeFromSuperview];
        self.coverBtn=nil;
       
    }
    
}


-(void)changeProducts:(UIButton *)btn
{
    //把之前的红色按钮背景色变成白色
    if (self.redButton==btn) {
        return;
    }
    
    self.redButton.backgroundColor=[UIColor whiteColor];
    //点击哪个按钮，就把那个按钮的背景色修改为红色
    btn.backgroundColor=[UIColor redColor];
    
    self.redButton=btn;
    
    [self.allClassButton setTitle:btn.currentTitle forState:UIControlStateNormal];
    
    self.redButtonIndex=(int)btn.tag;
    
    
    //获取选中的category模型，cids
    NSIndexPath *selectedIndexPath=self.categoryTable.indexPathForSelectedRow;
    UPOrderCategoryModel *categoryModel=self.categoryDataSource[selectedIndexPath.row];
    NSArray *cids=categoryModel.cids;
    
    UPOederAllClassModel *model=cids[btn.tag];
    
    
    
    //1.清空productDateSource中的数据
    [self.productDateSource removeAllObjects];
    if (model.iid==0) {
    
        [self.productDateSource addObjectsFromArray:self.productDataSourBak];
    }else{
    
    for (UPOrderProductModel *productModel in self.productDataSourBak) {
        if (productModel.child_cid==model.iid) {
            [self.productDateSource addObject:productModel];
        }
    
    }
    }
    [self.productTableView reloadData ];
    
    [self removeCover];
}
-(void)hideButtonView
{
    [self removeCover];
}
//综合排序按钮的点击事件
- (IBAction)btnSortClick:(id)sender {
    UPHButton *hbtn=(UPHButton *)sender;
    UIImageView *imgView=hbtn.imageView;
    [UIView animateWithDuration:0.5 animations:^{
    imgView.transform=CGAffineTransformRotate(imgView.transform, -M_PI);
    }];
    
    if (self.rightView) {
        [self.rightView removeFromSuperview];
        self.rightView=nil;
        
        [self.coverBtn1 removeFromSuperview];
        self.coverBtn1=nil;
        return;
    }
    if (self.buttonView) {
        [self.buttonView removeFromSuperview];
        self.buttonView=nil;
        
        [self.coverBtn removeFromSuperview];
        self.coverBtn=nil;
        
        UIImageView *imgView=self.allClassButton.imageView;
        [UIView animateWithDuration:0.5 animations:^{
        imgView.transform=CGAffineTransformRotate(imgView.transform, -M_PI);
        }];
        
        
    }
    
    
    UIView *rightView=[[UIView alloc] initWithFrame:CGRectMake(self.productTableView.x, self.productTableView.y, self.productTableView.width, self.productTableView.rowHeight)];
    
    self.rightView=rightView;
    rightView.backgroundColor=[UIColor whiteColor];
    
    [self.view addSubview:rightView];
    
    //间距
    int margin=5;
    int btnH=30;
    CGFloat btnW=(self.productTableView.bounds.size.width-4*margin)*0.33;
    for (int i=0; i<4; i++) {
        int col=i%3;//确定列
        int row=i/3;//确定行
        //计算X坐标
        CGFloat btnX=margin+(margin+btnW)*col;
        //计算Y坐标
        CGFloat btnY=margin+(margin+btnH)*row;
        
        
        UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(btnX, btnY, btnW, btnH)];
        
        btn.tag=i;
        //按钮的点击事件
        [btn addTarget:self action:@selector(changeClick:) forControlEvents:UIControlEventTouchUpInside];
        
        
        if (self.rightIndex>=0) {
            if (self.rightIndex==i) {
                self.rightButton=btn;
                [btn setBackgroundColor:[UIColor redColor]];
                
            }
        }else
        {
            if (i==0) {
                [btn setBackgroundColor:[UIColor redColor]];
                
                self.rightIndex=0;
                self.rightButton=btn;
            }
        }
        
        //字体大小
        btn.titleLabel.font=[UIFont systemFontOfSize:13];
        
        CALayer *layer=btn.layer;
        
        layer.borderColor=UPColor(169, 169, 169).CGColor;
        layer.borderWidth=1;
        layer.cornerRadius=5;
//        if (i==0) {
//            [btn setBackgroundColor:[UIColor redColor]];
//        }
        [self.rightView addSubview:btn];
        NSArray *arrName=@[@"综合排序",@"销量最高",@"价格最低",@"价格最高"];
        [btn setTitle:arrName[i] forState:UIControlStateNormal];
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    
        UIButton *coverBtn1=[[UIButton alloc] initWithFrame:CGRectMake(self.productTableView.x,rightView.height+self.productTableView.y , self.productTableView.width, self.productTableView.height-rightView.height)];
        self.coverBtn1=coverBtn1;
        
        
        coverBtn1.backgroundColor=[UIColor blackColor];
        coverBtn1.alpha=0.3;
        
        [coverBtn1 addTarget:self action:@selector(removeCoverRight) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:coverBtn1];
    
}
-(void)removeCoverRight
{
    
    UIImageView *imgView=self.sortButton.imageView;
    [UIView animateWithDuration:0.5 animations:^{
    imgView.transform=CGAffineTransformRotate(imgView.transform, -M_PI);
    }];
    
    if (self.rightView) {
        [self.rightView removeFromSuperview];
        self.rightView =nil;
        
        [self.coverBtn1 removeFromSuperview];
        self.coverBtn1=nil;
        
    }
    
    
    
}


-(void)changeClick:(UIButton *)btn
{
    
    
    //把之前的红色按钮背景色变成白色
    if (self.rightButton==btn) {
        return;
    }
    
    self.rightButton.backgroundColor=[UIColor whiteColor];
    //点击哪个按钮，就把那个按钮的背景色修改为红色
    btn.backgroundColor=[UIColor redColor];
    
    self.rightButton=btn;
    
    self.rightIndex=(int)btn.tag;
    

    /**
     *  排序
     */
        switch (btn.tag) {
            case 0:
                [self.productDateSource addObjectsFromArray:self.productDataSourBak];
                
                
                
                break;
                case 1:
                [self.sortButton setTitle:btn.currentTitle forState:UIControlStateNormal];
                [self.productDateSource sortUsingComparator:^NSComparisonResult(UPOrderProductModel *model1, UPOrderProductModel *model2) {
                    return model1.store_nums>model2.store_nums;
                    
                
                }];
                break;
                case 2:
                [self.sortButton setTitle:btn.currentTitle forState:UIControlStateNormal];
                [self.productDateSource sortUsingComparator:^NSComparisonResult(UPOrderProductModel *model1, UPOrderProductModel *model2) {
                    return model1.price>model2.price;
                }];
                break;
                case 3:
                [self.sortButton setTitle:btn.currentTitle forState:UIControlStateNormal];
                [self.productDateSource sortUsingComparator:^NSComparisonResult(UPOrderProductModel *model1, UPOrderProductModel *model2) {
                    return model1.price<model2.price;
                } ];
                break;
                
            default:
                break;
        
        
    }
    

    
    
    [self.productTableView reloadData];
    [self removeCoverRight];
    [self removeCover];
}


#pragma mark -tableview的数据源代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView==self.categoryTable) {
        return self.categoryDataSource.count;
    }
    return self.productDateSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==self.categoryTable) {
        
        
        //从缓存池中获取可用的Xib，若果没有，就以xib所对应的cell模板进行创建，
        UPOrderCategoryCell *cell=[tableView dequeueReusableCellWithIdentifier:CATEGORYCELLID];
        UPOrderCategoryModel *model=self.categoryDataSource[indexPath.row];
        
        cell.model=model;
        
        return cell;
        
        
    }else
    {
//        return [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"a"];
        UPOrderProductCell *cell=[tableView dequeueReusableCellWithIdentifier:PRODUCTCELLID];
        self.productTableView.rowHeight=88;
        UPOrderProductModel *model=self.productDateSource[indexPath.row];
        
        cell.model=model;
        return cell;
    }
    
}

#pragma mark tableView的代理方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==self.categoryTable) {
        /**
         * 1. 获取点击行所对应的模型
         */
        
        if (self.buttonView) {
            [self.buttonView removeFromSuperview];
            self.buttonView=nil;
            
            [self.coverBtn removeFromSuperview];
            self.coverBtn=nil;
            return;
        }
        
        if (self.rightView) {
            [self.rightView removeFromSuperview];
            self.rightView =nil;
            
            [self.coverBtn1 removeFromSuperview];
            self.coverBtn1=nil;
        }

        UPOrderCategoryModel *categoryModel=self.categoryDataSource[indexPath.row];
        
        /**
         *  2.获取主键
         */
        int iid=categoryModel.iid;
        NSString *idStr=[NSString stringWithFormat:@"%d",iid];
        
        /**
         *  3.根据主键从products字典中取出数组
         */
        NSArray *productArr=self.productsDict[idStr];
        /**
         *  4.遍历字典，转模型，删除之前的数据
         */
        [self.productDateSource removeAllObjects];
        
        [self.productDataSourBak removeAllObjects];
        
        for (NSDictionary *dict in productArr) {
            UPOrderProductModel *productModel=[UPOrderProductModel productWithDict:dict];
            [self.productDateSource addObject:productModel];
        }
        [self.productDataSourBak addObjectsFromArray:self.productDateSource];
        
        /**
         *  当点击cateforytableview时，全部分类排序返回原始状态
         */
        self.redButtonIndex=0;
        self.redButton.backgroundColor=[UIColor redColor];
        [self.allClassButton setTitle:@"全部分类" forState:UIControlStateNormal];
        /**
         *  当点击cateforytableview时，分类排序返回原始状态
         */
        self.redButton.backgroundColor=[UIColor redColor];
        self.redButtonIndex=0;
        [self.sortButton setTitle:@"综合排序" forState:UIControlStateNormal];
        
        /**
         *  5.重新刷新右边的tableview
         */
        
        [self.productTableView reloadData];
        [self removeCover];
        [self removeCoverRight];
    }else
    {
        UPOrderProductModel *productModel=self.productDateSource[indexPath.row];
        UPOrderProductDetailViewController *productVC=[[UPOrderProductDetailViewController alloc]init];
        
        productVC.productModel=productModel;
        
        //当把某个控制器push到导航控制器的时候，是否要隐藏导航控制器所在的tablebar控制器中的tabbar
        productVC.hidesBottomBarWhenPushed=YES;
        
        [self.navigationController pushViewController:productVC animated:YES];
        
        
    }
}
#pragma mark--定位的代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *currentLocation=[locations lastObject];
    //停止定位
    [manager stopUpdatingLocation];
   // NSLog(@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    
    CLGeocoder *coder=[[CLGeocoder alloc] init];
    [coder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *mark=placemarks[0];
       // NSLog(@"%@",mark.name);
        self.navigationItem.title=mark.name;
        
    }];
}

@end
